#include "InSdkRebootEveryday.h"
#include "InSdkTcpSystemClient.h"

#define DEF_TAG "Reboot"

#define DEF_REBOOR_TIME 2

Com_pvoid InSdkReboot_Thread(Com_pvoid arg)
{
    Com_u32 rand_min = 0;
    Com_u32 reboot_hour = 0;
    StComCurrentTime cur_time;

    while (Ext_InComFile_Access(DEF_FLAG_SYNC_TIME_OK) == DEF_COM_FILE_NOT_EXIST)
    {
        sleep(1);
    }

    /* Prevent multiple restart */
    Ext_InComTimer_GetLocalTime(&cur_time);
    if ((cur_time.hour == DEF_REBOOR_TIME) || (cur_time.hour == DEF_REBOOR_TIME + 1))
    {
        printf("don't restart this time\n");
        sleep(60 * 60 + 31 * 60);
    }

    srand((unsigned)time(NULL));
    rand_min = rand() % 90;

    /* rand_min >= 60 , hour is 3:00 */
    if (rand_min >= 60)
    {
        rand_min -= 60;
        reboot_hour++;
    }

    reboot_hour += DEF_REBOOR_TIME;
    PRT_INFO(DEF_TAG,"reboot hour: %d,minute: %d\n", reboot_hour, rand_min);

    DEF_COM_SET_THREAD_NAME("Reboot_Everyday",g_ComThread_Num);

    while (g_ComThread_Running)
    {
        Ext_InComTimer_GetLocalTime(&cur_time);
        printf("The time is %d:%d now\n", cur_time.hour, cur_time.min);
        if (cur_time.hour == (DEF_REBOOR_TIME + reboot_hour))
        {
            if (cur_time.min == rand_min)
            {
                printf("system reboot everyday \n");
                Ext_InSdkTcpSystem_Cmd("reboot");
                sleep(10);
            }
            else
            {
                sleep(60);
            }
        }
        else
        {
            printf("reboot everyday thread sleep %d minute\n", 60 - cur_time.min);
            sleep(60 * (60 - cur_time.min));
        }
    }

    DEF_COM_EXIT_THREAD(g_ComThread_Num);
}

Com_void Ext_InSdkReboot_Init(Com_void)
{
    return;

    pthread_t id;
    pthread_create(&id, NULL, InSdkReboot_Thread, NULL);
    pthread_detach(id);
}
